class order {
    constructor(..._data){ // 构造函数
        this.data = _data
    }
    data = null // 数据存放
    callbackList = [] // 回调列表
    endCallback = null // end方法回调
    errorCallback = null // 错误回调
    finallyCallback = null // 结束回调
    next(){
        const thid = this
        return function (..._data){
            thid.data = _data
            let callback
            try {
                if(thid.callbackList[0]){
                    callback = thid.callbackList.shift()

                    callback.resolve(thid.next(), ..._data)
                }else if(thid.endCallback){
                    thid.endCallback(...thid.data)
                }
            } catch (error) {
                if(callback.reject){
                    callback.reject(error, thid.next(), ..._data)
                }else{
                    setTimeout(()=>{
                        if(thid.errorCallback){
                            thid.errorCallback(error)
                        }else{
                            throw error
                        }
                    }, 0)
                }
            }
        }
    }
    then(fn1, fn2){
        if(!(fn1 instanceof Function)) throw Error('The parameter passed in by "then" must be a function')
        if(!(fn2 instanceof Function) && fn2) throw Error('The parameter passed in by "then" must be a function')
        const obj = {
            resolve:fn1,
            reject:fn2
        }
        this.callbackList.push(obj)
        return this
    }
    catch(fn){
        if(!(fn instanceof Function)) throw Error('The parameter passed in by "catch" must be a function')
        this.errorCallback = fn

        return this
    }
    end(fn){
        if(!(fn instanceof Function) && fn) throw Error('The parameter passed in by "end" must be a function')
        if(fn) this.endCallback = fn
        this.next()(...this.data)

        const thid = this
        return { 
            catch(fn_c){
                thid.catch.call(thid, fn_c)
            }
        }
    }
}


module.exports = order